//------------------------------------------------------------------------------
//  <copyright file="PoseSLAMGraphOptimizationTestAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------
namespace Test.Robotics.Navigation
{
    using System;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Navigation;
    using Microsoft.Robotics.Navigation.Runtime;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Numerics.GraphOptimization;
    using Microsoft.Robotics.Runtime;
    using ShoNS.Array;

    /// <summary>
    /// Class that loads in a graph of 2D Poses and optimizes it
    /// </summary>
    [DataContract]
    public class PoseSLAMGraphOptimizationTestAgent : ProducerAgent<GraphMessage>
    {
        /// <summary>
        /// file from which to load the file
        /// </summary>
        [DataMember]
        private string filename;

        /// <summary>
        /// Graph to optimize
        /// </summary>
        private Graph<Pose2D, Pose2DEdge> graph;

        /// <summary>
        /// Initializes a new instance of the PoseSLAMGraphOptimizationTestAgent class
        /// </summary>
        /// <param name="name">name of the agent</param>
        /// <param name="file">file of the graph to load</param>
        public PoseSLAMGraphOptimizationTestAgent(string name, string file)
            : base(name)
        {
            this.filename = file;
        }

        /// <summary>
        /// Initialize PoseSLAMGraphOptimizationAgent
        /// </summary>
        /// <param name="locator">Agent locator</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            Console.WriteLine(this.filename);
            this.graph = new Graph<Pose2D, Pose2DEdge>();
            this.LoadGraphFromFile();
        }

        /// <summary>
        /// On activated
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.PublishMessage));
            thread.Start();
        }

        /// <summary>
        /// Deactivates Agent
        /// </summary>
        public override void OnDeactivated()
        {
            base.OnDeactivated();
        }

        /// <summary>
        /// Publish a message every so often
        /// </summary>
        public void PublishMessage()
        {
            // gives the user 2.5 seconds to start the visualizer
            System.Threading.Thread.Sleep(2500); 
            while (true)
            {
                GraphMessage message = new GraphMessage(this.graph.Nodes, this.graph.Edges);
                this.Publisher.Post(message, true);
                Console.ReadKey(); // wait for user to hit a key
                Console.WriteLine("Optimizing...");
                this.graph.Optimize(Pose2DEdge.GlobalPoseError, Pose2DEdge.GlobalPoseIncrement);
                Console.WriteLine("Complete");
            }
        }

        /// <summary>
        /// Loads the graph from a file
        /// </summary>
        private void LoadGraphFromFile()
        {
            bool states = false;
            bool edges = false;
            System.IO.StreamReader reader = new System.IO.StreamReader(this.filename);
            while (reader.EndOfStream == false)
            {
                string data = reader.ReadLine();

                if (data == "STATES")
                {
                    states = true;
                    edges = false;
                    continue;
                }
                else if (data == "EDGES")
                {
                    states = false;
                    edges = true;
                    continue;
                }

                if (states)
                {
                    string[] parts = data.Split(' ');
                    Pose2D state = new Pose2D(Convert.ToDouble(parts[1]), Convert.ToDouble(parts[2]), Convert.ToDouble(parts[3]));
                    this.graph.AddNode(state);
                }
                else if (edges)
                {
                    string[] parts = data.Split(' ');
                    Pose2D measurement = new Pose2D(Convert.ToDouble(parts[2]), Convert.ToDouble(parts[3]), Convert.ToDouble(parts[4]));
                    int i = Convert.ToInt32(parts[0]);
                    int j = Convert.ToInt32(parts[1]);
                    this.graph.AddEdge(new Pose2DEdge(measurement, i, j));
                }
            }

            Console.WriteLine(this.graph);
            reader.Close();
        }
    }
}
